<template>
  <div class="manual-match-workbench">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <h1 class="page-title">手工匹配</h1>
        <div class="status-badges">
          <el-tag type="primary" class="total-badge">
            <el-icon><Document /></el-icon>
            待匹配交易: {{ stats.pendingTransactions }}
          </el-tag>
          <el-tag type="success" class="matched-badge">
            <el-icon><Connection /></el-icon>
            待确认匹配: {{ stats.pendingMatches }}
          </el-tag>
        </div>
      </div>
      
      <div class="header-actions">
        <!-- 匹配建议 -->
        <el-button 
          type="primary" 
          :icon="MagicStick" 
          @click="generateMatchSuggestions"
          :loading="suggestionLoading"
        >
          智能匹配建议
        </el-button>
        
        <!-- 批量操作 -->
        <el-button 
          :disabled="selectedItems.length === 0" 
          :icon="Check" 
          @click="batchConfirmMatches"
        >
          批量确认 ({{ selectedItems.length }})
        </el-button>
        
        <!-- 导出匹配结果 -->
        <el-button :icon="Download" @click="exportMatchResults">
          导出结果
        </el-button>
        
        <!-- 重新加载 -->
        <el-button :icon="Refresh" @click="reloadData">
          刷新数据
        </el-button>
      </div>
    </div>

    <!-- 统计概览卡片 -->
    <el-row :gutter="16" class="stats-cards">
      <el-col :span="6">
        <StatCard
          title="今日匹配数"
          :value="stats.todayMatches"
          type="primary"
          icon="Connection"
          :trend="stats.todayMatchesTrend"
        />
      </el-col>
      <el-col :span="6">
        <StatCard
          title="平均置信度"
          :value="stats.avgConfidence"
          suffix="%"
          type="warning"
          icon="DataAnalysis"
          :trend="stats.confidenceTrend"
        />
      </el-col>
      <el-col :span="6">
        <StatCard
          title="匹配准确率"
          :value="stats.accuracyRate"
          suffix="%"
          type="success"
          icon="SuccessFilled"
          :trend="stats.accuracyTrend"
        />
      </el-col>
      <el-col :span="6">
        <StatCard
          title="处理效率"
          :value="stats.efficiencyScore"
          suffix="分"
          type="info"
          icon="Opportunity"
          :trend="stats.efficiencyTrend"
        />
      </el-col>
    </el-row>

    <!-- 手工匹配工作区 -->
    <div class="workbench-main">
      <!-- 左侧：待匹配交易列表 -->
      <div class="panel-left" :style="{ width: leftPanelWidth + 'px' }">
        <el-card class="panel-card" shadow="never">
          <template #header>
            <div class="panel-header">
              <span>待匹配交易</span>
              <div class="panel-actions">
                <el-button 
                  :icon="Search" 
                  link 
                  @click="showTransactionFilter = !showTransactionFilter"
                >
                  筛选
                </el-button>
                <el-button :icon="Sort" link @click="sortTransactions">
                  排序
                </el-button>
              </div>
            </div>
          </template>
          
          <!-- 交易筛选 -->
          <el-collapse-transition>
            <div v-show="showTransactionFilter" class="panel-filter">
              <el-form :model="transactionFilter" inline>
                <el-form-item label="交易时间">
                  <el-date-picker
                    v-model="transactionFilter.dateRange"
                    type="daterange"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    value-format="YYYY-MM-DD"
                  />
                </el-form-item>
                
                <el-form-item label="金额范围">
                  <el-input-number
                    v-model="transactionFilter.minAmount"
                    :min="0"
                    placeholder="最小金额"
                    style="width: 120px"
                  />
                  <span style="margin: 0 8px">-</span>
                  <el-input-number
                    v-model="transactionFilter.maxAmount"
                    :min="0"
                    placeholder="最大金额"
                    style="width: 120px"
                  />
                </el-form-item>
                
                <el-form-item label="付款方">
                  <el-input
                    v-model="transactionFilter.payerName"
                    placeholder="输入付款方名称"
                    clearable
                    style="width: 150px"
                  />
                </el-form-item>
                
                <el-form-item>
                  <el-button type="primary" :icon="Search" @click="filterTransactions">
                    查询
                  </el-button>
                  <el-button :icon="Refresh" @click="resetTransactionFilter">
                    重置
                  </el-button>
                </el-form-item>
              </el-form>
            </div>
          </el-collapse-transition>
          
          <!-- 交易列表 -->
          <AdvancedTable
            ref="transactionTableRef"
            :data="transactions"
            :columns="transactionColumns"
            :loading="transactionLoading"
            :pagination="transactionPagination"
            row-key="id"
            @selection-change="handleTransactionSelection"
            @row-click="handleTransactionClick"
            @sort-change="handleTransactionSort"
            @size-change="handleTransactionSizeChange"
            @current-change="handleTransactionCurrentChange"
          />
        </el-card>
        
        <!-- 面板调整手柄 -->
        <div 
          class="panel-resize-handle"
          @mousedown="startResize('left')"
        ></div>
      </div>

      <!-- 中间：匹配操作区 -->
      <div class="panel-center">
        <el-card class="panel-card match-center-card" shadow="never">
          <template #header>
            <div class="panel-header">
              <span>匹配操作</span>
              <div class="match-indicator" v-if="selectedTransaction && selectedOrder">
                <el-tag type="success">已选择交易和订单</el-tag>
              </div>
            </div>
          </template>
          
          <div class="match-center-content">
            <!-- 匹配按钮组 -->
            <div class="match-actions">
              <el-button 
                type="primary" 
                size="large" 
                :icon="Connection"
                :disabled="!selectedTransaction || !selectedOrder"
                @click="confirmMatch"
                class="match-button"
              >
                确认匹配
              </el-button>
              
              <el-button 
                type="warning" 
                size="large" 
                :icon="Close"
                @click="clearSelection"
                class="clear-button"
              >
                清除选择
              </el-button>
            </div>
            
            <!-- 匹配详情 -->
            <div class="match-details" v-if="selectedTransaction && selectedOrder">
              <el-descriptions title="匹配详情" :column="1" border>
                <el-descriptions-item label="交易金额">
                  <span class="amount">{{ formatCurrency(selectedTransaction.amount) }}</span>
                </el-descriptions-item>
                <el-descriptions-item label="订单金额">
                  <span class="amount">{{ formatCurrency(selectedOrder.amount) }}</span>
                </el-descriptions-item>
                <el-descriptions-item label="金额差异">
                  <span :class="getAmountDiffClass()">
                    {{ formatCurrency(Math.abs(selectedTransaction.amount - selectedOrder.amount)) }}
                  </span>
                </el-descriptions-item>
                <el-descriptions-item label="时间差异">
                  {{ formatDateDiff(selectedTransaction.transactionDate, selectedOrder.orderDate) }}
                </el-descriptions-item>
                <el-descriptions-item label="匹配置信度">
                  <el-progress 
                    :percentage="calculateConfidence()" 
                    :status="calculateConfidence() > 80 ? 'success' : 'warning'" 
                  />
                </el-descriptions-item>
              </el-descriptions>
            </div>
            
            <!-- 匹配建议 -->
            <div class="match-suggestions" v-if="matchSuggestions.length > 0">
              <el-divider content-position="left">智能匹配建议</el-divider>
              <div class="suggestions-list">
                <div 
                  v-for="suggestion in matchSuggestions" 
                  :key="suggestion.id"
                  class="suggestion-item"
                  @click="applySuggestion(suggestion)"
                >
                  <div class="suggestion-info">
                    <div class="suggestion-title">
                      <el-icon><Lightning /></el-icon>
                      <span>建议匹配</span>
                    </div>
                    <div class="suggestion-details">
                      <span>{{ suggestion.transaction.payerName }}</span>
                      <span>{{ formatCurrency(suggestion.transaction.amount) }}</span>
                      <span>{{ suggestion.order.customerName }}</span>
                      <span>{{ formatCurrency(suggestion.order.amount) }}</span>
                    </div>
                  </div>
                  <div class="suggestion-confidence">
                    <el-tag :type="getConfidenceTagType(suggestion.confidence)">
                      置信度: {{ suggestion.confidence }}%
                    </el-tag>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </el-card>
      </div>

      <!-- 右侧：待匹配订单列表 -->
      <div class="panel-right" :style="{ width: rightPanelWidth + 'px' }">
        <el-card class="panel-card" shadow="never">
          <template #header>
            <div class="panel-header">
              <span>待匹配订单</span>
              <div class="panel-actions">
                <el-button 
                  :icon="Search" 
                  link 
                  @click="showOrderFilter = !showOrderFilter"
                >
                  筛选
                </el-button>
                <el-button :icon="Sort" link @click="sortOrders">
                  排序
                </el-button>
              </div>
            </div>
          </template>
          
          <!-- 订单筛选 -->
          <el-collapse-transition>
            <div v-show="showOrderFilter" class="panel-filter">
              <el-form :model="orderFilter" inline>
                <el-form-item label="订单时间">
                  <el-date-picker
                    v-model="orderFilter.dateRange"
                    type="daterange"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    value-format="YYYY-MM-DD"
                  />
                </el-form-item>
                
                <el-form-item label="金额范围">
                  <el-input-number
                    v-model="orderFilter.minAmount"
                    :min="0"
                    placeholder="最小金额"
                    style="width: 120px"
                  />
                  <span style="margin: 0 8px">-</span>
                  <el-input-number
                    v-model="orderFilter.maxAmount"
                    :min="0"
                    placeholder="最大金额"
                    style="width: 120px"
                  />
                </el-form-item>
                
                <el-form-item label="客户名称">
                  <el-input
                    v-model="orderFilter.customerName"
                    placeholder="输入客户名称"
                    clearable
                    style="width: 150px"
                  />
                </el-form-item>
                
                <el-form-item>
                  <el-button type="primary" :icon="Search" @click="filterOrders">
                    查询
                  </el-button>
                  <el-button :icon="Refresh" @click="resetOrderFilter">
                    重置
                  </el-button>
                </el-form-item>
              </el-form>
            </div>
          </el-collapse-transition>
          
          <!-- 订单列表 -->
          <AdvancedTable
            ref="orderTableRef"
            :data="orders"
            :columns="orderColumns"
            :loading="orderLoading"
            :pagination="orderPagination"
            row-key="id"
            @selection-change="handleOrderSelection"
            @row-click="handleOrderClick"
            @sort-change="handleOrderSort"
            @size-change="handleOrderSizeChange"
            @current-change="handleOrderCurrentChange"
          />
        </el-card>
        
        <!-- 面板调整手柄 -->
        <div 
          class="panel-resize-handle"
          @mousedown="startResize('right')"
        ></div>
      </div>
    </div>

    <!-- 底部状态栏 -->
    <div class="workbench-status-bar">
      <div class="status-info">
        <el-tag type="info">
          <el-icon><InfoFilled /></el-icon>
          已选择 {{ selectedItems.length }} 项，可进行批量操作
        </el-tag>
      </div>
      <div class="status-actions">
        <el-button 
          :disabled="selectedItems.length === 0" 
          @click="clearAllSelection"
        >
          清除所有选择
        </el-button>
      </div>
    </div>

    <!-- 匹配详情抽屉 -->
    <el-drawer
      v-model="detailsDrawerVisible"
      title="匹配详情"
      direction="rtl"
      size="600px"
    >
      <div class="match-detail-content" v-if="currentMatch">
        <el-descriptions title="交易信息" :column="1" border>
          <el-descriptions-item label="交易ID">
            {{ currentMatch.transaction.id }}
          </el-descriptions-item>
          <el-descriptions-item label="付款方">
            {{ currentMatch.transaction.payerName }}
          </el-descriptions-item>
          <el-descriptions-item label="交易金额">
            {{ formatCurrency(currentMatch.transaction.amount) }}
          </el-descriptions-item>
          <el-descriptions-item label="交易时间">
            {{ currentMatch.transaction.transactionDate }}
          </el-descriptions-item>
          <el-descriptions-item label="银行">
            {{ currentMatch.transaction.bankName }}
          </el-descriptions-item>
        </el-descriptions>
        
        <el-descriptions title="订单信息" :column="1" border class="order-info">
          <el-descriptions-item label="订单ID">
            {{ currentMatch.order.id }}
          </el-descriptions-item>
          <el-descriptions-item label="客户名称">
            {{ currentMatch.order.customerName }}
          </el-descriptions-item>
          <el-descriptions-item label="订单金额">
            {{ formatCurrency(currentMatch.order.amount) }}
          </el-descriptions-item>
          <el-descriptions-item label="订单时间">
            {{ currentMatch.order.orderDate }}
          </el-descriptions-item>
          <el-descriptions-item label="订单状态">
            <el-tag :type="getOrderStatusType(currentMatch.order.status)">
              {{ currentMatch.order.status }}
            </el-tag>
          </el-descriptions-item>
        </el-descriptions>
        
        <el-descriptions title="匹配信息" :column="1" border class="match-info">
          <el-descriptions-item label="匹配置信度">
            <el-progress 
              :percentage="currentMatch.confidence" 
              :status="currentMatch.confidence > 80 ? 'success' : 'warning'" 
            />
          </el-descriptions-item>
          <el-descriptions-item label="匹配时间">
            {{ currentMatch.matchedAt }}
          </el-descriptions-item>
          <el-descriptions-item label="匹配人">
            {{ currentMatch.matchedBy }}
          </el-descriptions-item>
          <el-descriptions-item label="匹配算法">
            {{ currentMatch.algorithm }}
          </el-descriptions-item>
        </el-descriptions>
      </div>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useReconciliationStore } from '@/stores/reconciliationStore'
import { useAppStore } from '@/stores/appStore'
import { 
  Search, Refresh, Download, Check, Close, 
  Connection, Sort, Document, MagicStick, InfoFilled,
  Lightning, SuccessFilled, DataAnalysis, Opportunity
} from '@element-plus/icons-vue'

// 组件导入
import AdvancedTable from '@/components/AdvancedTable.vue'
import StatCard from '@/components/StatCard.vue'

// API导入
import * as reconciliationAPI from '@/api/reconciliation'

// Store
const reconciliationStore = useReconciliationStore()
const appStore = useAppStore()

// 设置页面标题

// 类型定义
interface Transaction {
  id: string
  payerName: string
  amount: number
  transactionDate: string
  bankName: string
  status: string
  isSelected?: boolean
}

interface Order {
  id: string
  customerName: string
  amount: number
  orderDate: string
  status: string
  isSelected?: boolean
}

interface MatchSuggestion {
  id: string
  transaction: Transaction
  order: Order
  confidence: number
  algorithm: string
}

interface ManualMatchStats {
  pendingTransactions: number
  pendingMatches: number
  todayMatches: number
  avgConfidence: number
  accuracyRate: number
  efficiencyScore: number
  todayMatchesTrend: number
  confidenceTrend: number
  accuracyTrend: number
  efficiencyTrend: number
}

interface FilterParams {
  dateRange: string[]
  minAmount?: number
  maxAmount?: number
  payerName?: string
  customerName?: string
}

interface Pagination {
  page: number
  limit: number
  total: number
}

// 响应式数据
const transactionTableRef = ref()
const orderTableRef = ref()

const leftPanelWidth = ref(450)
const rightPanelWidth = ref(450)
const isResizing = ref(false)
const resizeDirection = ref<'left' | 'right'>('left')

const transactionLoading = ref(false)
const orderLoading = ref(false)
const suggestionLoading = ref(false)

const transactions = ref<Transaction[]>([])
const orders = ref<Order[]>([])
const selectedItems = ref<any[]>([])
const matchSuggestions = ref<MatchSuggestion[]>([])

const selectedTransaction = ref<Transaction | null>(null)
const selectedOrder = ref<Order | null>(null)
const currentMatch = ref<any>(null)

const detailsDrawerVisible = ref(false)

const showTransactionFilter = ref(false)
const showOrderFilter = ref(false)

// 筛选参数
const transactionFilter = reactive<FilterParams>({
  dateRange: [],
  minAmount: undefined,
  maxAmount: undefined,
  payerName: ''
})

const orderFilter = reactive<FilterParams>({
  dateRange: [],
  minAmount: undefined,
  maxAmount: undefined,
  customerName: ''
})

// 分页参数
const transactionPagination = reactive<Pagination>({
  page: 1,
  limit: 20,
  total: 0
})

const orderPagination = reactive<Pagination>({
  page: 1,
  limit: 20,
  total: 0
})

// 统计信息 (暂时使用模拟数据)
const stats = reactive<ManualMatchStats>({
  pendingTransactions: 156,
  pendingMatches: 23,
  todayMatches: 42,
  avgConfidence: 87.5,
  accuracyRate: 96.8,
  efficiencyScore: 92,
  todayMatchesTrend: 5.2,
  confidenceTrend: 1.8,
  accuracyTrend: 2.3,
  efficiencyTrend: 3.2
})

// 表格列定义
const transactionColumns = [
  { type: 'selection', width: 50 },
  { prop: 'payerName', label: '付款方', minWidth: 150 },
  { prop: 'amount', label: '金额', minWidth: 120, sortable: true },
  { prop: 'transactionDate', label: '交易时间', minWidth: 150, sortable: true },
  { prop: 'bankName', label: '银行', minWidth: 120 },
  { prop: 'status', label: '状态', minWidth: 100 }
]

const orderColumns = [
  { type: 'selection', width: 50 },
  { prop: 'customerName', label: '客户名称', minWidth: 150 },
  { prop: 'amount', label: '金额', minWidth: 120, sortable: true },
  { prop: 'orderDate', label: '订单时间', minWidth: 150, sortable: true },
  { prop: 'status', label: '状态', minWidth: 100 }
]

// 计算属性
const selectedItemsCount = computed(() => selectedItems.value.length)

// 方法
const loadTransactions = async () => {
  transactionLoading.value = true
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))
    
    // 模拟数据
    transactions.value = Array.from({ length: 20 }, (_, i) => ({
      id: `T${1000 + i}`,
      payerName: `付款方${i + 1}`,
      amount: Math.floor(Math.random() * 10000) + 1000,
      transactionDate: `2023-05-${String(i + 1).padStart(2, '0')}`,
      bankName: ['工商银行', '建设银行', '农业银行', '中国银行'][i % 4],
      status: ['pending', 'matched'][i % 2]
    }))
    
    transactionPagination.total = 156
  } catch (error) {
    ElMessage.error('加载交易数据失败')
  } finally {
    transactionLoading.value = false
  }
}

const loadOrders = async () => {
  orderLoading.value = true
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))
    
    // 模拟数据
    orders.value = Array.from({ length: 20 }, (_, i) => ({
      id: `O${2000 + i}`,
      customerName: `客户${i + 1}`,
      amount: Math.floor(Math.random() * 10000) + 1000,
      orderDate: `2023-05-${String(i + 1).padStart(2, '0')}`,
      status: ['pending', 'confirmed'][i % 2]
    }))
    
    orderPagination.total = 234
  } catch (error) {
    ElMessage.error('加载订单数据失败')
  } finally {
    orderLoading.value = false
  }
}

const handleTransactionSelection = (selection: Transaction[]) => {
  selectedItems.value = [...selection, ...selectedItems.value.filter(item => item.customerName)]
  if (selection.length > 0) {
    selectedTransaction.value = selection[0]
  } else {
    selectedTransaction.value = null
  }
}

const handleOrderSelection = (selection: Order[]) => {
  selectedItems.value = [...selectedItems.value.filter(item => item.payerName), ...selection]
  if (selection.length > 0) {
    selectedOrder.value = selection[0]
  } else {
    selectedOrder.value = null
  }
}

const handleTransactionClick = (row: Transaction) => {
  selectedTransaction.value = row
  ElMessage.info(`已选择交易: ${row.payerName}`)
}

const handleOrderClick = (row: Order) => {
  selectedOrder.value = row
  ElMessage.info(`已选择订单: ${row.customerName}`)
}

const confirmMatch = async () => {
  if (!selectedTransaction.value || !selectedOrder.value) {
    ElMessage.warning('请先选择交易和订单')
    return
  }
  
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 800))
    
    ElMessage.success(`成功匹配交易 ${selectedTransaction.value.payerName} 和订单 ${selectedOrder.value.customerName}`)
    
    // 重新加载数据
    loadTransactions()
    loadOrders()
    
    // 清除选择
    clearSelection()
  } catch (error) {
    ElMessage.error('匹配失败')
  }
}

const clearSelection = () => {
  selectedTransaction.value = null
  selectedOrder.value = null
  if (transactionTableRef.value) {
    transactionTableRef.value.clearSelection()
  }
  if (orderTableRef.value) {
    orderTableRef.value.clearSelection()
  }
  ElMessage.info('已清除选择')
}

const generateMatchSuggestions = async () => {
  suggestionLoading.value = true
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    // 模拟匹配建议数据
    matchSuggestions.value = Array.from({ length: 3 }, (_, i) => ({
      id: `S${100 + i}`,
      transaction: {
        id: `T${1000 + i}`,
        payerName: `付款方${i + 1}`,
        amount: Math.floor(Math.random() * 10000) + 1000,
        transactionDate: `2023-05-${String(i + 1).padStart(2, '0')}`,
        bankName: '工商银行',
        status: 'pending'
      },
      order: {
        id: `O${2000 + i}`,
        customerName: `客户${i + 1}`,
        amount: Math.floor(Math.random() * 10000) + 1000,
        orderDate: `2023-05-${String(i + 1).padStart(2, '0')}`,
        status: 'pending'
      },
      confidence: Math.floor(Math.random() * 30) + 70,
      algorithm: ['金额优先', '时间窗口', '综合算法'][i % 3]
    }))
    
    ElMessage.success('已生成3条匹配建议')
  } catch (error) {
    ElMessage.error('生成匹配建议失败')
  } finally {
    suggestionLoading.value = false
  }
}

const applySuggestion = (suggestion: MatchSuggestion) => {
  selectedTransaction.value = suggestion.transaction
  selectedOrder.value = suggestion.order
  ElMessage.success(`已应用匹配建议: ${suggestion.transaction.payerName} ↔ ${suggestion.order.customerName}`)
}

const batchConfirmMatches = async () => {
  if (selectedItems.value.length === 0) {
    ElMessage.warning('请先选择要确认的匹配项')
    return
  }
  
  try {
    await ElMessageBox.confirm(
      `确定要确认 ${selectedItems.value.length} 个匹配项吗？`,
      '批量确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    ElMessage.success(`成功确认 ${selectedItems.value.length} 个匹配项`)
    selectedItems.value = []
    loadTransactions()
    loadOrders()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('批量确认失败')
    }
  }
}

const exportMatchResults = () => {
  ElMessage.info('导出功能待实现')
}

const reloadData = () => {
  loadTransactions()
  loadOrders()
  ElMessage.success('数据已刷新')
}

const sortTransactions = () => {
  ElMessage.info('交易列表排序')
  // 这里可以添加具体的排序逻辑
}

const sortOrders = () => {
  ElMessage.info('订单列表排序')
  // 这里可以添加具体的排序逻辑
}

const filterTransactions = () => {
  ElMessage.success('交易筛选条件已应用')
  loadTransactions()
}

const resetTransactionFilter = () => {
  Object.assign(transactionFilter, {
    dateRange: [],
    minAmount: undefined,
    maxAmount: undefined,
    payerName: ''
  })
  ElMessage.success('交易筛选条件已重置')
  loadTransactions()
}

const filterOrders = () => {
  ElMessage.success('订单筛选条件已应用')
  loadOrders()
}

const resetOrderFilter = () => {
  Object.assign(orderFilter, {
    dateRange: [],
    minAmount: undefined,
    maxAmount: undefined,
    customerName: ''
  })
  ElMessage.success('订单筛选条件已重置')
  loadOrders()
}

const handleTransactionSort = (sort: any) => {
  ElMessage.info(`交易按 ${sort.prop} ${sort.order} 排序`)
}

const handleOrderSort = (sort: any) => {
  ElMessage.info(`订单按 ${sort.prop} ${sort.order} 排序`)
}

const handleTransactionSizeChange = (size: number) => {
  transactionPagination.limit = size
  transactionPagination.page = 1
  loadTransactions()
}

const handleTransactionCurrentChange = (page: number) => {
  transactionPagination.page = page
  loadTransactions()
}

const handleOrderSizeChange = (size: number) => {
  orderPagination.limit = size
  orderPagination.page = 1
  loadOrders()
}

const handleOrderCurrentChange = (page: number) => {
  orderPagination.page = page
  loadOrders()
}

const clearAllSelection = () => {
  selectedItems.value = []
  selectedTransaction.value = null
  selectedOrder.value = null
  if (transactionTableRef.value) {
    transactionTableRef.value.clearSelection()
  }
  if (orderTableRef.value) {
    orderTableRef.value.clearSelection()
  }
  ElMessage.info('已清除所有选择')
}

const startResize = (direction: 'left' | 'right') => {
  isResizing.value = true
  resizeDirection.value = direction
  
  const handleMouseMove = (e: MouseEvent) => {
    if (!isResizing.value) return
    
    if (direction === 'left') {
      leftPanelWidth.value = Math.max(300, Math.min(800, e.clientX - 20))
    } else {
      rightPanelWidth.value = Math.max(300, Math.min(800, window.innerWidth - e.clientX - 20))
    }
  }
  
  const handleMouseUp = () => {
    isResizing.value = false
    document.removeEventListener('mousemove', handleMouseMove)
    document.removeEventListener('mouseup', handleMouseUp)
  }
  
  document.addEventListener('mousemove', handleMouseMove)
  document.addEventListener('mouseup', handleMouseUp)
}

const calculateConfidence = () => {
  if (!selectedTransaction.value || !selectedOrder.value) return 0
  
  // 简单的置信度计算逻辑
  const amountDiff = Math.abs(selectedTransaction.value.amount - selectedOrder.value.amount)
  const amountSimilarity = 100 - (amountDiff / Math.max(selectedTransaction.value.amount, selectedOrder.value.amount) * 100)
  
  // 假设时间差异在7天内为高相似度
  const timeDiff = Math.abs(
    new Date(selectedTransaction.value.transactionDate).getTime() - 
    new Date(selectedOrder.value.orderDate).getTime()
  )
  const timeSimilarity = timeDiff < 7 * 24 * 60 * 60 * 1000 ? 100 : 50
  
  return Math.round((amountSimilarity * 0.7 + timeSimilarity * 0.3))
}

const getAmountDiffClass = () => {
  if (!selectedTransaction.value || !selectedOrder.value) return ''
  
  const diff = Math.abs(selectedTransaction.value.amount - selectedOrder.value.amount)
  if (diff === 0) return 'diff-zero'
  if (diff < 100) return 'diff-small'
  if (diff < 1000) return 'diff-medium'
  return 'diff-large'
}

const getConfidenceTagType = (confidence: number) => {
  if (confidence >= 90) return 'success'
  if (confidence >= 70) return 'warning'
  return 'danger'
}

const getOrderStatusType = (status: string) => {
  switch (status) {
    case 'pending': return 'warning'
    case 'confirmed': return 'success'
    case 'cancelled': return 'danger'
    default: return 'info'
  }
}

const formatCurrency = (amount: number) => {
  return `¥${amount.toLocaleString('zh-CN', { minimumFractionDigits: 2 })}`
}

const formatDateDiff = (date1: string, date2: string) => {
  const diff = Math.abs(
    new Date(date1).getTime() - new Date(date2).getTime()
  )
  const days = Math.floor(diff / (24 * 60 * 60 * 1000))
  return days === 0 ? '同一天' : `${days}天`
}

// 生命周期
onMounted(() => {
  loadTransactions()
  loadOrders()
})
</script>

<style scoped lang="scss">
.manual-match-workbench {
  height: 100%;
  display: flex;
  flex-direction: column;
  
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 20px;
    
    .header-left {
      .page-title {
        margin: 0 0 12px 0;
        font-size: 24px;
        font-weight: 600;
        color: #1f2d3d;
      }
      
      .status-badges {
        display: flex;
        gap: 12px;
        
        .el-tag {
          display: flex;
          align-items: center;
          gap: 4px;
          font-weight: 500;
        }
      }
    }
    
    .header-actions {
      display: flex;
      gap: 12px;
    }
  }
  
  .stats-cards {
    margin-bottom: 20px;
  }
  
  .workbench-main {
    flex: 1;
    display: flex;
    gap: 16px;
    overflow: hidden;
    margin-bottom: 16px;
    
    .panel-left,
    .panel-right {
      position: relative;
      height: 100%;
      
      .panel-card {
        height: 100%;
        display: flex;
        flex-direction: column;
        
        :deep(.el-card__header) {
          padding: 12px 20px;
          border-bottom: 1px solid #f0f0f0;
        }
        
        :deep(.el-card__body) {
          flex: 1;
          padding: 16px;
          overflow: auto;
        }
      }
      
      .panel-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        
        .panel-actions {
          display: flex;
          gap: 12px;
        }
      }
      
      .panel-filter {
        margin-bottom: 16px;
        padding: 16px;
        background-color: #f5f7fa;
        border-radius: 4px;
        
        :deep(.el-form-item) {
          margin-bottom: 12px;
        }
      }
    }
    
    .panel-center {
      flex: 1;
      height: 100%;
      
      .match-center-card {
        height: 100%;
        display: flex;
        flex-direction: column;
        
        :deep(.el-card__body) {
          flex: 1;
          display: flex;
          flex-direction: column;
        }
      }
      
      .match-center-content {
        flex: 1;
        display: flex;
        flex-direction: column;
        gap: 20px;
      }
      
      .match-actions {
        display: flex;
        justify-content: center;
        gap: 20px;
        padding: 20px 0;
        
        .match-button {
          width: 150px;
          height: 50px;
          font-size: 16px;
        }
        
        .clear-button {
          width: 120px;
          height: 50px;
          font-size: 16px;
        }
      }
      
      .match-details {
        .amount {
          font-weight: 600;
          font-size: 16px;
          color: #1f2d3d;
        }
        
        .diff-zero {
          color: #67c23a;
        }
        
        .diff-small {
          color: #e6a23c;
        }
        
        .diff-medium {
          color: #f56c6c;
        }
        
        .diff-large {
          color: #f56c6c;
          font-weight: 600;
        }
      }
      
      .match-suggestions {
        .suggestions-list {
          display: flex;
          flex-direction: column;
          gap: 12px;
        }
        
        .suggestion-item {
          display: flex;
          justify-content: space-between;
          align-items: center;
          padding: 12px 16px;
          border: 1px solid #dcdfe6;
          border-radius: 4px;
          cursor: pointer;
          transition: all 0.3s;
          
          &:hover {
            border-color: #409eff;
            background-color: #ecf5ff;
          }
          
          .suggestion-info {
            flex: 1;
            
            .suggestion-title {
              display: flex;
              align-items: center;
              gap: 8px;
              margin-bottom: 8px;
              font-weight: 500;
              color: #1f2d3d;
            }
            
            .suggestion-details {
              display: flex;
              gap: 20px;
              font-size: 14px;
              color: #606266;
            }
          }
          
          .suggestion-confidence {
            margin-left: 16px;
          }
        }
      }
    }
    
    .panel-resize-handle {
      position: absolute;
      top: 0;
      right: -8px;
      width: 16px;
      height: 100%;
      cursor: col-resize;
      z-index: 100;
      
      &::after {
        content: '';
        position: absolute;
        top: 0;
        left: 7px;
        width: 2px;
        height: 100%;
        background-color: #dcdfe6;
        transition: background-color 0.3s;
      }
      
      &:hover::after {
        background-color: #409eff;
      }
    }
    
    .panel-right .panel-resize-handle {
      left: -8px;
      right: auto;
    }
  }
  
  .workbench-status-bar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 12px 20px;
    background-color: #f5f7fa;
    border-radius: 4px;
    
    .status-info {
      .el-tag {
        display: flex;
        align-items: center;
        gap: 4px;
      }
    }
  }
  
  .match-detail-content {
    .order-info {
      margin: 20px 0;
    }
    
    .match-info {
      margin-top: 20px;
    }
  }
}
</style>